package cn.cellcom.agent.util;

import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.cellcom.agent.common.AgentConstant.ThirdCallback;
import cn.cellcom.agent.online.client.IDManager;
import net.sf.json.JSONObject;

public class ThirdCallbackUtils {

	private static Logger log = LoggerFactory.getLogger(ThirdCallbackUtils.class);

	static HttpParams httpClientParams = new BasicHttpParams();
	/**
	 */
	private static final int HTTP_CONNECTION_TIMEOUT = 3000;
	/**
	 */
	private static final int HTTP_REQUEST_TIMEOUT = 5000;
	static {
		HttpConnectionParams.setConnectionTimeout(httpClientParams, HTTP_CONNECTION_TIMEOUT);
		HttpConnectionParams.setSoTimeout(httpClientParams, HTTP_REQUEST_TIMEOUT);
	}

	/**
	 * 
	 * @param thirdCallback
	 * @param tid
	 * @param accessKey
	 * @param callUrl
	 * @param params
	 * @param object
	 * @return
	 */
	public static String call(ThirdCallback thirdCallback, String tid, String accessKey, String callUrl, Map<String, Object> params, Object object) {
		log.debug("[ThirdCallbackUtils.sendCallbackEvent] tid={}, accessKey={}, callUrl={}, params={} ", tid, accessKey, callUrl);
		if (params == null) {
			params = new HashMap<String, Object>();
		}
		if(tid == null || "null".equals(tid)) {
			tid = "";
		}
		HttpClient client = null;
		String res = null;
		try {
			if (callUrl.startsWith("https://")) {
				client = new SSLClient();
			} else {
				client = new DefaultHttpClient();
			}
			String timestamp = String.valueOf(System.currentTimeMillis());
			String token = IDManager.getToken(tid, timestamp, accessKey);
			HttpPost request = new HttpPost(callUrl);
			request.setParams(httpClientParams);
			params.put("type", thirdCallback.name());
			params.put("tid", tid);
			params.put("timestamp", timestamp);
			params.put("token", token);
			params.put("object", object);
			String json = JSONObject.fromObject(params).toString();
			StringEntity entity = new StringEntity(json, "UTF-8");
			entity.setContentType("application/json");
			request.setEntity(entity);
			HttpResponse response = client.execute(request);
			HttpEntity entitys = response.getEntity();
			int statusCode = response.getStatusLine().getStatusCode();
			if (HttpStatus.SC_OK == statusCode) {
				if (entitys != null) {
					res = EntityUtils.toString(entitys, "UTF-8");
				}
			} else {
				log.warn("[ThirdCallbackUtils.sendCallbackEvent]statusCode={}", statusCode);
			}
		} catch (Exception e) {
			log.error("[ThirdCallbackUtils.sendCallbackEvent] occur exception", e);
		} finally {
			if (client != null && client.getConnectionManager() != null) {
				client.getConnectionManager().shutdown();
			}
		}

		log.info("[ThirdCallbackUtils.sendCallbackEvent] get result = {}", res);
		return res;
	}
}
